package com.deer.wms.project.root.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.omg.CORBA.NameValuePair;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;




public class HttpClient {
    public static String client(String url, HttpMethod method, MultiValueMap<String, String> params) {
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        //  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        //  执行HTTP请求
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        return response.getBody();
    }

    public static void main(String[] args){
//        MultiValueMap<String, String> stringMultiValueMap = new LinkedMultiValueMap<>();
//        stringMultiValueMap.add("taskNo", "123");
//
//        String aaa = HttpClient.client("https://www.zhihu.com/question/27400704", HttpMethod.GET, stringMultiValueMap);
//        System.out.println(aaa);

        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> map1 = new HashMap<>();
        map1.put("ART_ARTICOLO","TEST1");
        map1.put("ART_DES","TEST1");
        Map<String, String> map2 = new HashMap<>();
        map2.put("ART_ARTICOLO","TEST2");
        map2.put("ART_DES","TEST2");
        list.add(map1);
        list.add(map2);
        Map<String , List<Map<String, String>>> m = new HashMap<>();
        m.put("IMP_ARTICOLI",list);
        String s = JSONArray.toJSONString(m);


        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost("http://127.0.0.1:3001/api/jobs/CFG-IMP-ARTICOLI");
        System.out.println("要发送的数据" + JSON.toJSONString(m));
        StringEntity myEntity = new StringEntity(JSON.toJSONString(m), ContentType.APPLICATION_JSON);// 构造请求数据
        post.addHeader("Authorization", getHeader());
        post.setEntity(myEntity);// 设置请求体
        String responseContent = null; // 响应内容
        CloseableHttpResponse response = null;
        try {
            response = client.execute(post);
            System.out.println(JSON.toJSONString(response));
            if (response.getStatusLine().getStatusCode() == 200) {
                System.out.println("sucess");
//                HttpEntity entity = response.getEntity();
//                responseContent = EntityUtils.toString(entity, "UTF-8");
            }
            System.out.println("responseContent:" + responseContent);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null)
                    response.close();

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (client != null)
                        client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }




    }


    public static Map<String, String> requestERP(String body, String url, HttpMethod method) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("access-token", "123456");
        HttpEntity<String> requestEntity = new HttpEntity<>(body, headers);
        RestTemplate client = new RestTemplate();
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        String res = response.getBody();
        JSONObject object = JSON.parseObject(res);
        Boolean success = object.getBoolean("success");
        String code = object.getString("code");
        String msg = object.getString("message");
        Map<String, String> map = new HashMap<>();
        map.put("success", success != null ? success.toString() : "false");
        map.put("message", msg);
        map.put("code", code);
        return map;
    }

    public static String clientRg(String url, HttpMethod method, MultiValueMap<String, String> params) throws Exception {
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        //  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        //  执行HTTP请求
        //加两步骤
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                System.out.println("Warning: URL Host: " + urlHostName + " vs. "
                        + session.getPeerHost());
                return true;
            }
        };
        trustAllHttpsCertificates();
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        return response.getBody();
    }

    private static void trustAllHttpsCertificates() throws Exception {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
                .getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
                .getSocketFactory());
    }

    static class miTM implements javax.net.ssl.TrustManager,
            javax.net.ssl.X509TrustManager {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }
    }

    public static String getRequest(String url, MultiValueMap<String, String> params, HttpHeaders headers) throws Exception {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(0);// 设置建立连接超时时间
        requestFactory.setReadTimeout(0);// 设置等待返回超时时间

        RestTemplate client = new RestTemplate(requestFactory);
        HttpMethod method = HttpMethod.GET;
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        System.out.println(response.getBody());
        return response.getBody();
    }

    public static String getRequestByPost(String url, MultiValueMap<String, String> params, HttpHeaders headers) throws Exception {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(0);// 设置建立连接超时时间
        requestFactory.setReadTimeout(0);// 设置等待返回超时时间

        RestTemplate client = new RestTemplate(requestFactory);
        HttpMethod method = HttpMethod.POST;
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        System.out.println(response.getBody());
        return response.getBody();
    }

    public static String getHeader() {
        String auth = "ADVANCED" + ":" + "SYSTEM08";
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
        String authHeader = "Basic " + new String(encodedAuth);
        return authHeader;
    }

}
